package com.situ.stmall.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.situ.stmall.entity.User;

/**
 * 拦截器的写法
 * 1. 创建一个类, 实现HandlerInterceptor
 * 2. 加上@Component
 * 3. 实现相应的方法
 * 4. 创建一个SpringMVC的配置类, 实现WebMvcConfigurer接口
 * 5. 实现addInterceptors的方法, 添加拦截路径和放行路径
 * 
 * @author bobzyh
 *
 */
@Component
public class UserInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 判断用户是否登录
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		
		if (user != null) {
			// 用户已登录, 直接放行
			return true;
		} else {
			// 跳转到登录页面
			response.sendRedirect("/user/login");
			return false;
		}
	}
}




